(function (global, factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        module.exports = factory(global, true)
    } else {
        factory(global)
    }
})(typeof window !== "undefined" ? window : this, function (window, noGlobal) {
    // 延时函数 类似 pyhton sleep
    function delay(duration = 1000) {
        const start = Date.now();
        while (Date.now() - start < duration) { }
    }

    // 动画指定某个列表下的元素们都有此动画
    class Flip {
        constructor(obj, time) {
            this.time = time || 0.8;
            this.targetItems = [];
            this.startArr = [];
            if (Array.isArray(obj)) {
                this.targetItems = document.querySelector(obj)
            } else {
                this.targetItems = obj
            }
            this.init()
        }

        raf(callback) {
            requestAnimationFrame(() => {
                requestAnimationFrame(callback);
            })
        }

        // 拿指定元素的位置
        getLocation(tt) {
            // getBoundingClientRect 拿到的是相对浏览器视窗的位置
            const rect = tt.getBoundingClientRect();
            return {
                top: rect.top,
                left: rect.left
            };
        }

        // 触发变动
        play() {
            for (let i = 0; i < this.targetItems.length; i++) {
                let item = this.targetItems[i];
                let { top, left } = this.getLocation(item);
                // delay(500)

                let topDis = 0;
                let leftDis = 0;
                for (let j = 0; j < this.startArr.length; j++) {
                    const itemStart = this.startArr[j];
                    if (itemStart.item === item) {
                        topDis = itemStart.top - top;
                        leftDis = itemStart.left - left;
                    }
                }

                if (topDis === 0 && leftDis === 0) {
                    // console.log('都没变 不动');
                    continue;
                }

                item.style.transform = `translate(${leftDis}px, ${topDis}px)`;

                (function (that, item) {
                    setTimeout(() => {

                        that.raf(() => {
                            item.style.transition = `transform ${that.time}s`
                            item.style.removeProperty('transform');
                        })
                    }, 12);
                })(this, item)

            }
        }

        // 初始化
        init() {
            this.startArr = [];
            for (let i = 0; i < this.targetItems.length; i++) {
                let item = this.targetItems[i];
                let { top, left } = this.getLocation(item);
                this.startArr.push({
                    item,
                    top,
                    left
                })
            }
        }
    }
    if (typeof noGlobal === "undefined") {
        window.Flip = Flip
    }
    return Flip
})